package com.leonwoodstudio.endorsementclient;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    public TextView status_message;
    ContentReceiver receiver;
    ImageView imageView;
    MenuItem current_user;
    AlertDialog ip_port_dialog;
    AlertDialog.Builder select_user_dialog;

    String prop_default_user;
    String prop_all_users;
    String prop_local_port;
    String prop_remote_port;
    String prop_remote_ip_address;
    String local_ip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        status_message = (TextView) findViewById(R.id.status_message);
        FileAccessor.getInstance(this);
        Util.getProperties(this);
        loadProperties();
        local_ip = Util.getHostIP();
        current_user = navigationView.getMenu().findItem(R.id.current_user);
        current_user.setTitle("当前用户: " + prop_default_user);

        Button[] buttons = new Button[9];
        int[] button_ids = new int[]{
                R.id.button0, R.id.button1, R.id.button2,
                R.id.button3, R.id.button4, R.id.button5,
                R.id.button6, R.id.button7, R.id.button8};
        for (int i = 0; i < buttons.length; i++) {
            buttons[i] = (Button) findViewById(button_ids[i]);
            final int command = i;
            buttons[i].setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new SendCommandAsyncTask(MainActivity.this, prop_remote_ip_address, prop_remote_port).execute(command);
                        }
                    }
            );
        }

        imageView = (ImageView) findViewById(R.id.received_pic);

        Intent intent = new Intent(this, MainService.class);
        intent.putExtra("local_port", prop_local_port);
        startService(intent);

        receiver = new ContentReceiver();
        IntentFilter filter = new IntentFilter(Util.ACTION_FILE_RECEIVED);
        registerReceiver(receiver, filter);

        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            status_message.setText("外存不可用,请检查手机状态!");
        }

        buildIpPortDialog();
        buildSelectUserDialog();
    }

    private void buildIpPortDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("地址端口信息");
        builder.setPositiveButton("确定", null);
        View view = View.inflate(this, R.layout.ip_port_dialog, null);
        builder.setView(view);
        TextView local_ip_port = (TextView) view.findViewById(R.id.local_ip_port);
        TextView remote_ip_port = (TextView) view.findViewById(R.id.remote_ip_port);
        local_ip_port.setText(local_ip + " : " + prop_local_port);
        remote_ip_port.setText(prop_remote_ip_address + " : " + prop_remote_port);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        ip_port_dialog = builder.create();
    }

    private void buildSelectUserDialog() {
        final String[] all_users = prop_all_users.split(",");
        select_user_dialog = new  AlertDialog.Builder(this)
                .setTitle("请选择当前用户" )
                .setIcon(R.mipmap.ic_launcher)
                .setSingleChoiceItems(all_users, -1, null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ListView lv = ((AlertDialog)dialog).getListView();
                        int selected = lv.getCheckedItemPosition();
                        prop_default_user = all_users[selected];
                        Properties props = Util.getProperties(MainActivity.this);
                        props.put(Util.PROPERTIES_KEY_DEFAULT_USER, prop_default_user);
                        Util.saveProperties(props);
                        current_user.setTitle("当前用户: " + all_users[selected]);
                    }
                })
                .setNegativeButton("取消" ,  null );
    }

    private void loadProperties() {
        prop_default_user = Util.getProperties(this).getProperty(Util.PROPERTIES_KEY_DEFAULT_USER);
        prop_all_users = Util.getProperties(this).getProperty(Util.PROPERTIES_KEY_ALL_USERS);
        prop_local_port = Util.getProperties(this).getProperty(Util.PROPERTIES_KEY_LOCAL_PORT);
        prop_remote_port = Util.getProperties(this).getProperty(Util.PROPERTIES_KEY_REMOTE_PORT);
        prop_remote_ip_address = Util.getProperties(this).getProperty(Util.PROPERTIES_KEY_REMOTE_IP_ADDRESS);
    }

    private void showReceivedPic(String file) {
        try {
            FileInputStream fis = new FileInputStream(new File(file));
            Bitmap bm = BitmapFactory.decodeStream(fis);
            imageView.setImageBitmap(bm);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    private class ContentReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int type = intent.getIntExtra("type", MainService.MSG_RECV_FAIL);
            String file = intent.getStringExtra("file");
            if (type == MainService.MSG_RECV_FAIL) {
                status_message.setText("接收推送文件失败,请检查网络和服务器端是否正常!");
            } else if (type == MainService.MSG_RECV_PIC) {
                showReceivedPic(FileAccessor.getInstance(null).getFilesDir() + file);
            } else if (type == MainService.MSG_RECV_XML) {
                new ParseXmlAsyncTask(MainActivity.this).execute(FileAccessor.getInstance(null).getFilesDir() + file);
            }
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_select_user) {
            select_user_dialog.show();
        } else if (id == R.id.nav_ip_port) {
            ip_port_dialog.show();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
